package com.efast.cafe.commponent.es.socketio.listener;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;

import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.efast.cafe.commponent.es.socketio.properties.SocketIOConfig;
import com.efast.cafe.commponent.es.socketio.util.SocketIOUtil;
import com.efast.cafe.framework.constant.FrameConstant;
import com.efast.cafe.framework.json.JSONObject;
import com.efast.cafe.framework.spring.SpringContextUtils;
import com.efast.cafe.util.ConfigUtil;
import com.efast.cafe.util.date.DateUtils;

/**
 * 
    * @ClassName: SocketIOConnectListener
    * @Description: socket io 客户端连接上后
    * @author xuanming.feng
    * @date 2018年11月1日
    *
 */
public class SocketIOConnectListener implements ConnectListener{
	private final static Logger log = LoggerFactory.getLogger(SocketIOConnectListener.class);
	
	private StringRedisTemplate redisTemplate;
	private SocketIOConfig config;
	public SocketIOConnectListener(SocketIOConfig config){
		this.config = config;
	}
	
	
	@Override
	public void onConnect(SocketIOClient client) {
		HandshakeData data = client.getHandshakeData();
		List<String> info = data.getUrlParams().get(FrameConstant.SOCKET_UID);
		String uid = info.get(0);
		client.set(FrameConstant.SOCKET_UID, uid);
		String clientIp = client.getHandshakeData().getAddress().toString();
		 log.info("client :"+uid+" , 连接上socket.io server.IP:"+client.getHandshakeData().getAddress().toString());
		
		SocketIOUtil.puSocketIOClient(uid, client);
		 try{
			 redisTemplate = SpringContextUtils.getBean(StringRedisTemplate.class);
			 JSONObject jo = new JSONObject();
			 jo.put("clientIP", clientIp);
			 jo.put("onLineTime", DateUtils.format(new Date(), DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS_SSS));
			 BoundHashOperations<String,String,String> redisOper = redisTemplate.boundHashOps(FrameConstant.SOCKET_IO_ONLINE_TOKEN+":"+config.getInstance());
			 redisOper.put(uid, jo.toString());
			 redisOper.expire(120, TimeUnit.SECONDS);
		 }catch(Exception e){
			 log.error("put socket on-line user error:",e);
			 client.disconnect();
		 }
	}
	
	
	

}
